package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import com.heima.utils.common.AppThreadLocalUtil;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ArticleSearchServiceImpl implements ArticleSearchService {
    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private ApUserSearchService apUserSearchService;

    /**
     * 文章搜索
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {
        //2. 创建查询对象
        SearchRequest searchRequest = new SearchRequest("app_info_article");

        //4. 创建条件构建期对象
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        //6. 创建Bool查询
        BoolQueryBuilder booleanQueryBulder = QueryBuilders.boolQuery();

        //7. 设置查询的条件
        if(StringUtils.isNotEmpty(dto.getSearchWords())){
            booleanQueryBulder.must(QueryBuilders
                    .queryStringQuery(dto.getSearchWords())
                    .field("title")
                    .field("content")
                    .defaultOperator(Operator.OR));
            ApUser apUser = AppThreadLocalUtil.get();

            if(null != apUser){
                apUserSearchService.insert(dto.getSearchWords(), apUser.getId());
            }

        }else{
            booleanQueryBulder.must(QueryBuilders.matchAllQuery());
        }

        //8. 设置过滤的条件
        booleanQueryBulder.filter(QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime()));

        //5. 设置查询的条件
        sourceBuilder.query(booleanQueryBulder);

        //9. 设置分页
        sourceBuilder.from(dto.getPageNum() * dto.getPageSize());
        sourceBuilder.size(dto.getPageSize());

        //10. 高亮设置
        HighlightBuilder highlighter = new HighlightBuilder();
        highlighter.field("title");
        highlighter.preTags("<font style='color: red; font-size: inherit;'>");
        highlighter.postTags("</font>");

        sourceBuilder.highlighter(highlighter);

        //添加排序规则
        sourceBuilder.sort("publishTime", SortOrder.DESC);

        //3. 设置查询的条件构建期对象
        searchRequest.source(sourceBuilder);
        //1. 查询的入海
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        //解析结果数据
        SearchHits hits = searchResponse.getHits();
        long total = hits.getTotalHits().value; // 总记录数

        SearchHit[] searchHits = hits.getHits(); // 获取命中的数据
        List<Map> list = null;

        if(null != searchHits && searchHits.length > 0){
            list = new ArrayList<>(searchHits.length);

            for (SearchHit searchHit : searchHits) {
                String json = searchHit.getSourceAsString();

                Map map = JSON.parseObject(json, Map.class);

                //解析高亮数据
                Map<String, HighlightField> highlightFieldMap = searchHit.getHighlightFields();
                if(null != highlightFieldMap && highlightFieldMap.size() > 0){
                    HighlightField highlightField = highlightFieldMap.get("title");
                    Text[] fragments = highlightField.getFragments();

                    map.put("h_title", StringUtils.join(fragments));
                }else{
                    map.put("h_title", map.get("title"));
                }


                list.add(map);
            }
        }

        return ResponseResult.okResult(list);
    }
}
